package com.csthink.mr.wordcount;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;

/**
 * @author <a href="mailto:csthink@icloud.com">Mars</a>
 * @since 2024-04-12 16:59
 */
public class WordCountReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
    @Override
    protected void setup(Context context) throws IOException, InterruptedException {
        System.out.println("WordCountReducer-setup");
    }

    /**
     * 相同的key经过shuffle之后，会在同一个reduce中进行聚合
     * 默认按字典排序
     * @param k2
     * @param v2s
     * @param context
     * @throws IOException
     * @throws InterruptedException
     */
    @Override
    protected void reduce(Text k2, Iterable<IntWritable> v2s, Context context) throws IOException, InterruptedException {
        int sum = 0;
        for (IntWritable v2 : v2s) {
            sum += v2.get();
        }

        context.write(k2, new IntWritable(sum));
    }

    @Override
    protected void cleanup(Reducer<Text, IntWritable, Text, IntWritable>.Context context) throws IOException, InterruptedException {
        System.out.println("WordCountReducer-cleanup");
    }
}
